package org.byqh.dqeai.controller;

import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.byqh.dqeai.common.Json;
import org.byqh.dqeai.dto.EaiSysRoleUserDTO;
import org.byqh.dqeai.dto.EaiSysUserRoleDTO;
import org.byqh.dqeai.dto.common.PageData;
import org.byqh.dqeai.entity.EaiSysUserRole;
import org.byqh.dqeai.entity.proxy.EaiSysUserRoleProxy;
import org.byqh.dqeai.enums.SystemEnum;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;

@RestController
@RequestMapping("/sysuserrole")
@Tag(name = "系统[EaiSysUserRole] - 用户角色管理")
public class EaiSysUserRoleController extends BaseController<EaiSysUserRole, EaiSysUserRoleProxy> {
    @Override
    @GetMapping(value = "/get/{id}")
    public Json<EaiSysUserRole> get(String id) {
        return super.get(id);
    }

    @Override
    @PutMapping(value = "/put")
    public Json<Boolean> put(EaiSysUserRole dto) {
        return super.put(dto);
    }

    @Override
    @PostMapping(value = "/post")
    public Json<Boolean> post(EaiSysUserRole dto) {
        return super.post(dto);
    }

    /**
     * 新增某一个具体对象信息
     */
    @PostMapping(value = "/")
    public Json<Boolean> post(@RequestBody EaiSysUserRoleDTO dto) {
        var now = LocalDateTime.now();

        dto.setUpdateDate(now);
        dto.setCreateDate(now);

        return easyEntityQuery.insertable(dto).executeRows() > 0 ? Json.success() : Json.error();
    }

    /**
     * 删除某一个具体对象信息
     */
    @DeleteMapping(value = "/{sysUserId}/{roleId}")
    public Json<Boolean> delete(@PathVariable String sysUserId, @PathVariable String roleId) {
        if (StringUtils.isBlank(sysUserId) || StringUtils.isBlank(roleId)) {
            return Json.errorT(SystemEnum.USER_OPREATION_ENUM.OPERATION_FAIL.getValue());
        }

        return getEntityDeletable().where(e -> e.roleId().eq(roleId))
                .where(e -> e.userId().eq(sysUserId))
                .executeRows() > 0 ? Json.success() : Json.error();
    }

    /**
     * 修改某一个具体对象信息
     */
    @PutMapping(value = "/")
    public Json<Boolean> put(@RequestBody EaiSysUserRoleDTO dto) {
        return Json.success();
    }

    /**
     * 查询对象信息分页列表
     */
    @PostMapping(value = "/page")
    public Json<PageData<EaiSysUserRoleDTO>> page(@RequestParam(defaultValue = "1") Integer page,
                                                  @RequestParam(defaultValue = "10") Integer size,
                                                  @RequestParam(defaultValue = "", required = false) String sort,
                                                  @RequestBody(required = false) EaiSysUserRoleDTO dto) {
        var pageData = this.listPageImpl(EaiSysUserRoleDTO.class, page, size, null).getData();
        return Json.success(new PageData<>(pageData));
    }

    /**
     * 查询全部对象信息列表
     */
    @GetMapping(value = "/list")
    public Json<List<EaiSysUserRoleDTO>> list() {
        return this.listAll(new EaiSysUserRoleDTO());
    }

    /**
     * 查询全部对象信息列表
     */
    @PostMapping(value = "/listAll")
    public Json<List<EaiSysUserRoleDTO>> listAll(@RequestBody(required = false) EaiSysUserRoleDTO dto) {
        return this.listImpl(EaiSysUserRoleDTO.class, query -> {
            if (dto.getRoleIdList() != null) {
                query = query.where(o -> o.roleId().in(dto.getRoleIdList()));
            }

            return query;
        });
    }

    /**
     * 更新用户关联的角色
     */
    @PostMapping(value = "/deleteAndInsert")
    public Json<Boolean> deleteAndInsert(@RequestBody(required = false) EaiSysUserRoleDTO dto) {

        // 1.参数验证
        if (dto == null || StringUtils.isBlank(dto.getUserId())) {
            return Json.errorT(SystemEnum.USER_OPREATION_ENUM.PARAMS_NULL.getValue());
        }

        // 2.删除：根据appId在用户角色表中查询所有的角色，根据角色和用户ID去删除用户角色表的数据
        this.getEntityDeletable().where(e -> e.roleId().in(
                easyEntityQuery.queryable(EaiSysUserRole.class)
                        .where(a -> a.userId().eq(dto.getUserId()))
                        .select(a -> a.roleId())
        )).executeRows();

        // 3.新增
        var list = new LinkedList<EaiSysUserRole>();
        var now = LocalDateTime.now();
        for (String roleId : dto.getRoleIdList()) {
            EaiSysUserRole entity = new EaiSysUserRole();
            entity.setCreateDate(now);
            entity.setUpdateDate(now);
            entity.setRoleId(roleId);
            entity.setUserId(dto.getUserId());
            list.add(entity);
        }
        this.saveBatch(list);

        return Json.success(true);
    }

    /**
     * 更新角色关联的用户
     */
    @PostMapping(value = "/deleteAndInsertByRole")
    public Json<Boolean> deleteAndInsert(@RequestBody(required = false) EaiSysRoleUserDTO dto) {
        // 1.参数验证
        if (dto == null || StringUtils.isBlank(dto.getRoleId())) {
            return Json.errorT(SystemEnum.USER_OPREATION_ENUM.PARAMS_NULL.getValue());
        }

        // 2.删除：根据appId在用户角色表中查询所有的角色，根据角色和用户ID去删除用户角色表的数据
        this.getEntityDeletable()
                .where(e -> e.roleId().eq(dto.getRoleId()))
                .executeRows();

        // 3.新增
        var list = new LinkedList<EaiSysUserRole>();
        var now = LocalDateTime.now();
        for (String userId : dto.getUserIdList()) {
            EaiSysUserRole entity = new EaiSysUserRole();
            entity.setCreateDate(now);
            entity.setUpdateDate(now);
            entity.setRoleId(dto.getRoleId());
            entity.setUserId(userId);
            list.add(entity);
        }
        this.saveBatch(list);

        return Json.success(true);
    }
}